package com.mytrans.util;

import com.google.gson.JsonIOException;
import com.zhou.util.JsonUtil;
import feign.Response;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.Type;

import static feign.Util.ensureClosed;

public class ServletUtil {

    public static String getRequestBody(HttpServletRequest request) throws IOException {
        String body;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()))){
            StringBuffer buffer = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null){
                buffer.append(line);
            }
            body = buffer.toString();
        }
        return body;
    }

    public static HttpServletRequest getRequest(){
        ServletRequestAttributes ra= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request =  ra.getRequest();
        return request;
    }

    public static byte[] obj2Body(Object obj){
        byte[] bytes = null;
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)){
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray ();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }

    public static <T> T decode(Response response, Type type) throws IOException {
        if (response.status() != 200) {
            throw new RuntimeException("远程mytrans服务器异常，无法访问, status=" + response.status());
        }
        if (response.body() == null) {
            return null;
        }
        Reader reader = response.body().asReader();
        try {
            return JsonUtil.getGson().fromJson(reader, type);
        } catch (JsonIOException e) {
            if (e.getCause() != null && e.getCause() instanceof IOException) {
                throw IOException.class.cast(e.getCause());
            }
            throw e;
        } finally {
            ensureClosed(reader);
        }
    }

}
